﻿using System;
using System.Text;
using System.Security.Cryptography;
using umbraco.cms.businesslogic.media;

namespace Decode.Umb
{
	public class Hash
	{
		static public string GetMediaMd5Sum(Media m)
		{
			// get string of unique media values
			string plaintekst = m.UniqueId + m.User.Name + m.Version + m.VersionDate.ToString("yyyyMMddHHmmss");

			// First we need to convert the string into bytes, which
			// means using a text encoder.
			Encoder enc = System.Text.Encoding.Unicode.GetEncoder();

			// Create a buffer large enough to hold the string
			byte[] unicodeText = new byte[plaintekst.Length * 2];
			enc.GetBytes(plaintekst.ToCharArray(), 0, plaintekst.Length, unicodeText, 0, true);

			// Now that we have a byte array we can ask the CSP to hash it
			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] result = md5.ComputeHash(unicodeText);

			// Build the final string by converting each byte
			// into hex and appending it to a StringBuilder
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < result.Length; i++)
			{
				sb.Append(result[i].ToString("X2"));
			}

			// And return it
			return sb.ToString();
		}
	}
}